//
//  ViewController.m
//  自定制相机
//
//  Created by MyMac on 15/7/4.
//  Copyright (c) 2015年 MyMac. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "MJViewController.h"
#import "MJMoviePlayerViewController.h"
@interface ViewController ()<AVCaptureFileOutputRecordingDelegate,MJMoviePlayerViewControllerDelegate>
@property(nonatomic,strong)AVCaptureSession*captureSession;
@property(nonatomic,strong)AVCaptureMovieFileOutput*output;
@property(nonatomic,strong)AVCaptureConnection*captureConnection;
@property(nonatomic,strong)AVCaptureDeviceInput*deviceInput;
@property(nonatomic,strong)AVCaptureVideoPreviewLayer*previewLayer;
@property(nonatomic,strong)MJMoviePlayerViewController*playerController;
@property(nonatomic,copy)NSString*videoUrl;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
 /*调用相机设备四个重要的类AVCaptureSession AVCaptureDeviceInput
  AVCaptureMovieFileOutput AVCaptureVideoPreviewLayer
  
  AVCaptureSession沟通AVCaptureDeviceInput 和AVCaptureMovieFileOutput（AVCaptureOutput的子类）
  
  AVCaptureDeviceInput链接一个硬件设备，比如摄像头，麦克风，等
  AVCaptureMovieFileOutput输出一个视频文件，还可以输出一个照片文件，具体什么类查下文档，都是AVCaptureOutput的子类
  
  */
    self.captureSession=[[AVCaptureSession alloc]init];
    if([self.captureSession canSetSessionPreset:AVCaptureSessionPresetHigh]){
        self.captureSession.sessionPreset=AVCaptureSessionPresetHigh;//这个属性是设置拍摄的效果的，如果需要更细的设置，可以设置AVCaptureDevice的activeFormat属性
        
    }
   // AVCaptureDevice*device=[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDevice*device=[self getCameraDeviceWithPosition:AVCaptureDevicePositionBack];//获取后置摄像头
    NSError*e1=nil;
    BOOL lockDetail= [device lockForConfiguration:&e1];//一下为设置硬件设备的一些属性，可以设置闪关灯，曝光度等，设置设备的格式前需要加锁lockForConfiguration，完了后解锁unlockForConfiguration
    if(lockDetail){
        NSError*error;
        CMTime frameDuration=CMTimeMake(1, 60);
        NSArray*supportedFrameRateRanges=[device.activeFormat videoSupportedFrameRateRanges];//设备的捕获格式
        BOOL frameRateSupported=NO;
        for(AVFrameRateRange*range in supportedFrameRateRanges){
            
            if(CMTIME_COMPARE_INLINE(frameDuration, >=, range.minFrameDuration)&&CMTIME_COMPARE_INLINE(frameDuration, <=, range.maxFrameDuration)){
                frameRateSupported=YES;
                
                
                
            }
            
            
        }
        
        if(frameRateSupported&&[device lockForConfiguration:&error]){
            
            [device setActiveVideoMaxFrameDuration:frameDuration];
            [device setActiveVideoMinFrameDuration:frameDuration];//在设备捕获格式的范围内设置帧速率，一帧的时长等于帧速率的倒数
            
            
            
        }
        
        NSLog(@"e1:%@",e1);
        [device unlockForConfiguration];
    }
    
    
    
    
    
    
    NSError*error=nil;
    AVCaptureDeviceInput*cameraDeviceInput=[[AVCaptureDeviceInput alloc]initWithDevice:device error:&error];//链接一个硬件设备
    
   
    self.deviceInput=cameraDeviceInput;
    NSLog(@"错误：%@",error);
    if([self.captureSession canAddInput:self.deviceInput]){
        
        [self.captureSession addInput:self.deviceInput];//加到会话中
        
    }

    AVCaptureMovieFileOutput*movieOutPut=[[AVCaptureMovieFileOutput alloc]init];
    if([self.captureSession canAddOutput:movieOutPut]){
        
        [self.captureSession addOutput:movieOutPut];//将文件输出加到会话中
    }
    self.output=movieOutPut;
   
    
    
    AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];//预览层，，，有了这个就可以看到拍摄的画面
    
    // set size
    CGRect bounds=CGRectMake(0, 0, self.view.bounds.size.width, 200) ;
    captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    captureVideoPreviewLayer.bounds=bounds;
    captureVideoPreviewLayer.position=CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));
    self.previewLayer=captureVideoPreviewLayer;
    [self.view.layer addSublayer:captureVideoPreviewLayer];
    
    
    
    AVCaptureVideoStabilizationMode stabilizationMode=AVCaptureVideoStabilizationModeCinematic;
    if([device.activeFormat isVideoStabilizationModeSupported:stabilizationMode]){
        
        [self.captureConnection setPreferredVideoStabilizationMode:stabilizationMode];//拍摄防抖动
        
    }
    
    //device.videoHDREnabled=YES;//高动态范围图像
    // NSString*path=NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)[0];
    
   
   
   
    
    //[self.captureSession startRunning];//开始会话

}
- (IBAction)btnClick:(id)sender {
     AVCaptureConnection *captureConnection=[self.output connectionWithMediaType:AVMediaTypeVideo];
    if([self.captureSession canAddConnection:captureConnection]){
    
        [self.captureSession addConnection:captureConnection];//设置链接
    }

    NSString*str=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString*s=[[NSDate date] description];
    NSString*path=[str stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",s]];
    self.videoUrl=path;
    NSURL*outputURL=[NSURL fileURLWithPath:[str stringByAppendingPathComponent:path]];//文件名必须是一个可用的视频格式文件
   // NSLog(@"%@   %@   %@",movieOutPut,self,outputURL);
    // [self.captureSession commitConfiguration];
    [self.captureSession startRunning];
    [self.output startRecordingToOutputFileURL:outputURL recordingDelegate:self];//录像开始，这一步很重要

    
    

}
-(AVCaptureDevice *)getCameraDeviceWithPosition:(AVCaptureDevicePosition )position{
    NSArray *cameras= [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *camera in cameras) {
        if ([camera position]==position) {
            return camera;
        }
    }
    return nil;
}
- (IBAction)stop:(id)sender {
    
    [self.output stopRecording];
    [self.captureSession stopRunning];//停止录制
    
    
}
//代理
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didStartRecordingToOutputFileAtURL:(NSURL *)fileURL fromConnections:(NSArray *)connections;
{

    NSLog(@"开始%@",fileURL);

}
- (BOOL)captureOutputShouldProvideSampleAccurateRecordingStart:(AVCaptureOutput *)captureOutput
{
    return YES;

}
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error;
{
   

    
    //完成录制
//    ALAssetsLibrary*assetLabrary=[[ALAssetsLibrary alloc]init];
//    [assetLabrary writeVideoAtPathToSavedPhotosAlbum:outputFileURL completionBlock:^(NSURL *assetURL, NSError *error) {
//        NSLog(@"%@  &&&&&   %@",assetURL,error);
//    }];
    UISaveVideoAtPathToSavedPhotosAlbum(outputFileURL.path, self, @selector(saveVideo), nil);
//   BOOL a= UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(outputFileURL.path);
    

}
-(void)saveVideo

{
   
    
    
    NSLog(@"保存");

}
- (IBAction)player:(id)sender {
    
    MJMoviePlayerViewController*vc=[[MJMoviePlayerViewController alloc]init];
    vc.delegate=self;
    //NSString*str=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
   
    NSURL*outputURL=[NSURL fileURLWithPath:self.videoUrl];
    NSFileManager*manger=[NSFileManager defaultManager];
    if( [manger fileExistsAtPath:self.videoUrl]){
        vc.movieURL=outputURL;
        
        [self presentViewController:vc animated:YES completion:nil];
       // NSFileHandle*landle=[NSFileHandle fileHandleForReadingAtPath:path];
        
    
    }
   
}
- (MJMoviePlayerViewController *)playerController
{
    if (!_playerController) {
        _playerController = [[MJMoviePlayerViewController alloc] init];
        //_playerController.delegate = self;
        // _playerController.movieURL = [[NSBundle mainBundle] URLForResource:@"promo_full.mp4" withExtension:nil];
        _playerController.movieURL=[NSURL URLWithString:@"http://aivideos.qiniudn.com/movie.mp4"];
    }
    return _playerController;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (AVCaptureConnection *)captureConnection {
    
    AVCaptureConnection *videoConnection = nil;
    for (AVCaptureConnection *connection in self.output.connections)
    {
        for (AVCaptureInputPort *port in [connection inputPorts])
        {
            if ([[port mediaType] isEqual:AVMediaTypeVideo]) {
                videoConnection = connection;
                break;
            }
        }
        if (videoConnection) {
            break;
        }
    }
    
    return videoConnection;
}
-(void)moviePlayerDidFinished
{

    [self dismissViewControllerAnimated:YES completion:nil];

}
@end
